const Koa = require('koa')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const { router }  = require('./middlewares/router')
const { database } = require('./middlewares/database')
const { addBody, addSession } = require('./middlewares/common')

class Server {
  constructor() {
    this.app = new Koa()
  }
  async start() {
    // Import and Set Nuxt.js options
    let config = require('../nuxt.config.js')
    config.dev = !(this.app.env === 'production')

    // Instantiate nuxt.js
    const nuxt = new Nuxt(config)
    
    const {
      host = process.env.HOST || '127.0.0.1',
      port = process.env.PORT || 3000
    } = nuxt.options.server
  
    // Build in development
    if (config.dev) {
      const builder = new Builder(nuxt)
      await builder.build()
    } else {
      await nuxt.ready()
    }

    database(this.app)
    addBody(this.app)
    addSession(this.app)
    router(this.app)
  
    this.app.use(ctx => {
      ctx.status = 200
      ctx.respond = false // Bypass Koa's built-in response handling
      ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash

      //后台缓存cookie
      ctx.req.session = ctx.session

      nuxt.render(ctx.req, ctx.res)
    })
  
    this.app.listen(2888, host)
    consola.ready({
      message: `Server listening on http://${host}:${2888}`,
      badge: true
    })
  }
}
const server = new Server()
server.start()
